package com.ezlcp.form.service;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ezlcp.commons.base.db.BaseDao;
import com.ezlcp.commons.base.db.BaseService;
import com.ezlcp.commons.constant.Constants;
import com.ezlcp.commons.constant.StatusEnum;
import com.ezlcp.commons.service.impl.SuperServiceImpl;
import com.ezlcp.commons.tool.IdGenerator;
import com.ezlcp.commons.tool.StringUtils;
import com.ezlcp.commons.utils.ContextUtil;
import com.ezlcp.form.entity.DicValue;
import com.ezlcp.form.entity.Dictionary;
import com.ezlcp.form.mapper.DictionaryMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.ezlcp.commons.constant.Constants.COL_TENANT_ID;


/**
 * [数据字典]业务服务类
 */
@Service
public class DictionaryServiceImpl extends SuperServiceImpl<DictionaryMapper, Dictionary> implements BaseService<Dictionary> {
    @Autowired
    private DictionaryMapper dictionaryMapper;

    @Resource
    private DicValueServiceImpl dicValueService;

    @Override
    public BaseDao<Dictionary> getRepository() {
        return dictionaryMapper;
    }

    /***
     * @description 保存字典数据和子表（下拉选项）
     * @param dict 数据字典
     * @param details 下拉选项
     * @param delIds 要删除的明细记录ID
     * @return java.lang.String
     * @author Elwin ZHANG
     * @date 2023/5/17 11:21
     */
    @Transactional
    public String saveDictAndValues(Dictionary dict, JSONArray details, String delIds) {
        String tenantId = ContextUtil.getCurrentTenantId();
        //主表是新增
        if (StringUtils.isEmpty(dict.getDicId())) {
            dict.setTenantId(tenantId);
            dict.setIsFixed(Constants.SHORT0);
            dict.setDicId(IdGenerator.getIdStr());
            this.dictionaryMapper.insert(dict);
        } else {
            //主表是编辑
            dict.setSeq(dict.getSeq() + 1);
            this.dictionaryMapper.updateById(dict);
        }
        String dicId = dict.getDicId();
        String dicKey = dict.getDicKey();
        //循环处理子表记录
        for (int i = 0; i < details.size(); i++) {
            var dicValue = details.getObject(i, DicValue.class);
            dicValue.setDicId(dicId);
            dicValue.setDicKey(dicKey);
            //新增的明细记录
            if (StringUtils.isEmpty(dicValue.getValId())) {
                dicValue.setTenantId(tenantId);
                dicValue.setIsFixed(Constants.SHORT0);
                dicValue.setValId(IdGenerator.getIdStr());
                this.dicValueService.insert(dicValue);
            } else {
                //修改的明细记录
                dicValue.setSeq(dicValue.getSeq() + 1);
                this.dicValueService.updateById(dicValue);
            }
        }
        //是否有要删除的子记录
        if (StringUtils.isEmpty(delIds)) {
            return "";
        }
        String[] ids = delIds.split(",");
        for (String id : ids) {
            if (StringUtils.isEmpty(id)) {
                continue;
            }
            var value = this.dicValueService.getById(id);
            if (value != null) {
                value.setStatus((short) StatusEnum.deleted.getValue());
                value.setSeq(value.getSeq() + 1);
                this.dicValueService.updateById(value);
            }
        }
        return "";
    }

    /***
     * @description 检查Key是否存在
     * @param dicKey key
     * @param dicId 当前记录ID
     * @return boolean
     * @author Elwin ZHANG
     * @date 2023/5/17 16:04
     */
    public boolean checkKeyRepeat(String dicKey, String dicId) {
        QueryWrapper<Dictionary> wrapper = new QueryWrapper();
        String tenantId = ContextUtil.getCurrentTenantId();
        if (StringUtils.isNotEmpty(tenantId)) {
            wrapper.eq(Constants.COL_TENANT_ID, tenantId);
        } else {
            wrapper.and(query -> query.eq(COL_TENANT_ID, "").or().isNull(COL_TENANT_ID));
        }
        wrapper.lambda().eq(Dictionary::getDicKey, dicKey).
                lt(Dictionary::getStatus, StatusEnum.deleted.getValue());
        if (StringUtils.isNotEmpty(dicId)) {
            wrapper.lambda().ne(Dictionary::getDicId, dicId);
        }
        var cnt = this.dictionaryMapper.selectCount(wrapper);
        if (cnt != null && cnt > 0) {
            return true;
        }
        return false;
    }

    /***
     * @description 逻辑删除数据字典
     * @param dicId 数据字典ID
     * @author Elwin ZHANG
     * @date 2023/5/17 15:18
     */
    public void delDict(String dicId) {
        var dic = this.dictionaryMapper.selectById(dicId);
        if (dic == null) {
            return;
        }
        dic.setStatus((short) StatusEnum.deleted.getValue());
        dic.setSeq(dic.getSeq() + 1);
        this.dictionaryMapper.updateById(dic);
    }

    /***
     * @description 获取数据字典记录以及其对应的下拉选项
     * @param id 字典ID
     * @return com.alibaba.fastjson2.JSONObject
     * @author Elwin ZHANG
     * @date 2023/5/11 15:53
     */
    public JSONObject getById(String id) {
        JSONObject result = new JSONObject();
        var dic = this.dictionaryMapper.selectById(id);
        if (dic == null) {
            return result;
        }
        result.put("master", dic);
        var values = dicValueService.getByDicId(id);
        result.put("details", values);
        return result;
    }

    /***
     * @description: 根据当前用户角色查询数据字典
     * @return java.util.List<com.ezlcp.user.entity.Dictionary> 符合角色要求字典列表
     * @author Weixuan LONG
     * @date 2022/5/11 10:12
     */
    public List<Dictionary> getByDicKey(String dicKeyList) {
        String[] dicKey = dicKeyList.split(",");
        QueryWrapper<Dictionary> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1);
        wrapper.and(query -> query.eq("is_fixed", 1).or().eq(Constants.COL_TENANT_ID, ContextUtil.getCurrentTenantId())).in("dic_key", dicKey);
        List<Dictionary> dictionaryList = dictionaryMapper.selectList(wrapper);
        // 查询子项列表
        dictionaryList.forEach(dictionary -> {
            List<DicValue> dicValueList = dicValueService.getByDicId(dictionary.getDicId());
            dictionary.setDicValueList(dicValueList);
        });
        return dictionaryList;
    }
}